<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico">
  <link rel="mask-icon" href="/images/favicon.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"wwwttttj.gitee.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="1.背景  官网地址：https:&#x2F;&#x2F;www.xuxueli.com&#x2F;xxl-job&#x2F;   博客:分布式对任务调度的几点要求  写的不错，大家可以看看 xxl-job 是比较成功的分布式调度任务,任务调度也是日常开发的常见业务场景。xxl-job 其解耦、ha&#x2F;集群、故障和阻塞处理、高性能、平台化和代码结构分明 等方面做的不错，值得我们进行学习。 下面根据源码分析 框架思想和实现技巧 2.解耦任务">
<meta property="og:type" content="article">
<meta property="og:title" content="分享框架中好的架构思想">
<meta property="og:url" content="https://wwwttttj.gitee.io/2020/09/27/%E5%88%86%E4%BA%AB%E6%A1%86%E6%9E%B6%E4%B8%AD%E5%A5%BD%E7%9A%84%E6%9E%B6%E6%9E%84%E6%80%9D%E6%83%B3/index.html">
<meta property="og:site_name" content="wwwblog">
<meta property="og:description" content="1.背景  官网地址：https:&#x2F;&#x2F;www.xuxueli.com&#x2F;xxl-job&#x2F;   博客:分布式对任务调度的几点要求  写的不错，大家可以看看 xxl-job 是比较成功的分布式调度任务,任务调度也是日常开发的常见业务场景。xxl-job 其解耦、ha&#x2F;集群、故障和阻塞处理、高性能、平台化和代码结构分明 等方面做的不错，值得我们进行学习。 下面根据源码分析 框架思想和实现技巧 2.解耦任务">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-09-27T07:57:54.000Z">
<meta property="article:modified_time" content="2020-09-27T07:58:45.965Z">
<meta property="article:author" content="wwwttttj">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://wwwttttj.gitee.io/2020/09/27/%E5%88%86%E4%BA%AB%E6%A1%86%E6%9E%B6%E4%B8%AD%E5%A5%BD%E7%9A%84%E6%9E%B6%E6%9E%84%E6%80%9D%E6%83%B3/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>分享框架中好的架构思想 | wwwblog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="wwwblog" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">wwwblog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-commonweal">

    <a href="/404/" rel="section"><i class="fa fa-heartbeat fa-fw"></i>公益 404</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wwwttttj.gitee.io/2020/09/27/%E5%88%86%E4%BA%AB%E6%A1%86%E6%9E%B6%E4%B8%AD%E5%A5%BD%E7%9A%84%E6%9E%B6%E6%9E%84%E6%80%9D%E6%83%B3/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="wwwttttj">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="wwwblog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          分享框架中好的架构思想
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-09-27 15:57:54 / 修改时间：15:58:45" itemprop="dateCreated datePublished" datetime="2020-09-27T15:57:54+08:00">2020-09-27</time>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="1-背景"><a href="#1-背景" class="headerlink" title="1.背景"></a>1.背景</h2><p>  官网地址：<a target="_blank" rel="noopener" href="https://www.xuxueli.com/xxl-job/">https://www.xuxueli.com/xxl-job/</a></p>
<p>  博客:分布式对任务调度的几点要求  写的不错，大家可以看看</p>
<p>xxl-job 是比较成功的分布式调度任务,任务调度也是日常开发的常见业务场景。xxl-job 其解耦、ha/集群、故障和阻塞处理<br>、高性能、平台化和代码结构分明 等方面做的不错，值得我们进行学习。</p>
<p>下面根据源码分析 框架思想和实现技巧</p>
<h2 id="2-解耦"><a href="#2-解耦" class="headerlink" title="2.解耦"></a>2.解耦</h2><p>任务调度 拆分为 调度和任务两个模块，相互独立，互不影响。</p>
<p>调度模块（调度中心）：负责管理任务信息，触发任务执行，自身不承担业务逻辑；</p>
<p>执行模块（执行器）： 负责接收调度中心请求，维护和运行任务逻辑；专注于任务执行相关操作；</p>
<h2 id="3-HA-集群-故障和阻塞处理"><a href="#3-HA-集群-故障和阻塞处理" class="headerlink" title="3. HA/集群  故障和阻塞处理"></a>3. HA/集群  故障和阻塞处理</h2><p>这部分后面代码里详细讲述</p>
<h2 id="4-高性能"><a href="#4-高性能" class="headerlink" title="4.高性能"></a>4.高性能</h2><p>使用了异步和netty 架构。通过队列的方式实现调度请求异步消费，提高了并发量。</p>
<h2 id="5-平台化，国际化"><a href="#5-平台化，国际化" class="headerlink" title="5.平台化，国际化"></a>5.平台化，国际化</h2><p>架构统一形成规范，降低人的学习成本</p>
<a id="more"></a>
<h1 id="代码分析"><a href="#代码分析" class="headerlink" title="代码分析"></a>代码分析</h1><p>xxl-job-admin 调度模块是一个spring-boot 简单的项目，通过http 对任务进行配置。com.xxl.job.admin.core.thread.JobScheduleHelper 这个类会不断扫描任务给执行模块的queue。<br>xxl-job-core 执行模块主要com.xxl.job.core.thread.JobThread这个类不断获取队列中的任务<br>注册流程 类：com.xxl.job.core.executor.XxlJobExecutor   分为三步</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; 1.init JobHandler Repository</span><br><span class="line">initJobHandlerRepository(applicationContext);</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 2.refresh GlueFactory</span><br><span class="line">GlueFactory.refreshInstance(1);</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; 3.super start</span><br><span class="line">super.start();</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>1.执行器先将自身注册到spring-ApplicationContext 中 并获取@JobHandler 注解的类上的name，最后保存进 jobHandlerRepository(ConcurrentHashMap&lt;String, IJobHandler&gt;)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">private void initJobHandlerRepository(ApplicationContext applicationContext)&#123;</span><br><span class="line"> …… ……</span><br><span class="line">    Map&lt;String, Object&gt; serviceBeanMap &#x3D; applicationContext.getBeansWithAnnotation(JobHandler.class);</span><br><span class="line"></span><br><span class="line">    if (serviceBeanMap!&#x3D;null &amp;&amp; serviceBeanMap.size()&gt;0) &#123;</span><br><span class="line">        for (Object serviceBean : serviceBeanMap.values()) &#123;</span><br><span class="line">            if (serviceBean instanceof IJobHandler)&#123;</span><br><span class="line">                String name &#x3D; serviceBean.getClass().getAnnotation(JobHandler.class).value();</span><br><span class="line">                IJobHandler handler &#x3D; (IJobHandler) serviceBean;</span><br><span class="line">                if (loadJobHandler(name) !&#x3D; null) &#123;</span><br><span class="line">                    throw new RuntimeException(&quot;xxl-job jobhandler naming conflicts.&quot;);</span><br><span class="line">                &#125;</span><br><span class="line">                registJobHandler(name, handler);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="2">
<li><p>实例化SpringGlueFactory  </p>
</li>
<li><p>初始化一下日志,初始化调度中心地址，日志清理功能，回调功能 和netty-http 向 调度中心的9999端口（默认）注册自己的地址（这里使用他自己写的xxl-rpc）</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">XxlJobFileAppender.initLogPath(logPath);</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; init invoker, admin-client</span><br><span class="line">initAdminBizList(adminAddresses, accessToken);</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; init JobLogFileCleanThread</span><br><span class="line">JobLogFileCleanThread.getInstance().start(logRetentionDays);</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; init TriggerCallbackThread</span><br><span class="line">TriggerCallbackThread.getInstance().start();</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; init executor-server</span><br><span class="line">port &#x3D; port&gt;0?port: NetUtil.findAvailablePort(9999);</span><br><span class="line">ip &#x3D; (ip!&#x3D;null&amp;&amp;ip.trim().length()&gt;0)?ip: IpUtil.getIp();</span><br><span class="line">initRpcProvider(ip, port, appName, accessToken);</span><br><span class="line"></span><br></pre></td></tr></table></figure>


</li>
</ol>
<p> 调度中心，调度任务通过实现spring的InitializingBean 启动了(JobScheduleHelper)线程去监听和执行任务 </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">  initI18n();</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; admin registry monitor run</span><br><span class="line">JobRegistryMonitorHelper.getInstance().start();</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; admin fail-monitor run</span><br><span class="line">JobFailMonitorHelper.getInstance().start();</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; admin lose-monitor run</span><br><span class="line">JobLosedMonitorHelper.getInstance().start();</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; admin trigger pool start</span><br><span class="line">JobTriggerPoolHelper.toStart();</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; admin log report start</span><br><span class="line">JobLogReportHelper.getInstance().start();</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; start-schedule</span><br><span class="line">JobScheduleHelper.getInstance().start();</span><br><span class="line"></span><br><span class="line">logger.info(&quot;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; init xxl-job admin success.&quot;);</span><br></pre></td></tr></table></figure>

<p>JobScheduleHelper  中route  找到合适的路由，通过 rpc 调用 ExecutorBiz 的方法,最终调用 pushTriggerQueue 放入客户端队列中。同时registJobThread<br>启动一个线程不断获取这个队列和执行这个任务。</p>
<p>可以看到 xxl-job 将调度中心和执行器分开，通过rpc 进行远程调用。最新的版本是启动netty http服务。实现了解耦，但是代码嘿嘿。</p>
<p>xxl-job 如何控制并发多个任务？？<br>调度中心的并发控制 ，是通过JobScheduleHelper类控制的。这个线程上面已经有了会不断获取任务，判断时间是否到来执行，<br>并发通过一句sql：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">preparedStatement &#x3D; conn.prepareStatement(  &quot;select * from xxl_job_lock where lock_name &#x3D; &#39;schedule_lock&#39; for update&quot; );</span><br><span class="line">preparedStatement.execute();</span><br></pre></td></tr></table></figure>
<p>来进行控制  select XX for update 进行锁表。</p>
<p>总结： xxl-job 使用数据库锁，对调度中心进行并发控制，通过ExecutorRouter 策略进行rpc 调用执行器。<br>故障和阻塞处理 使用线程不断查询处理。高性能 也只是高级版本用了netty框架。<br>框架的代码需要继续优化，还有不少未完成的模块。但是整体架构思想值得我们学习。</p>

    </div>

    
    
    

      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/09/24/springBeanpostProcess%E7%9A%84%E7%AE%80%E5%8D%95%E4%BB%8B%E7%BB%8D/" rel="prev" title="springBeanpostProcess的简单介绍">
      <i class="fa fa-chevron-left"></i> springBeanpostProcess的简单介绍
    </a></div>
      <div class="post-nav-item"></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E8%83%8C%E6%99%AF"><span class="nav-number">1.</span> <span class="nav-text">1.背景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E8%A7%A3%E8%80%A6"><span class="nav-number">2.</span> <span class="nav-text">2.解耦</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-HA-%E9%9B%86%E7%BE%A4-%E6%95%85%E9%9A%9C%E5%92%8C%E9%98%BB%E5%A1%9E%E5%A4%84%E7%90%86"><span class="nav-number">3.</span> <span class="nav-text">3. HA&#x2F;集群  故障和阻塞处理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E9%AB%98%E6%80%A7%E8%83%BD"><span class="nav-number">4.</span> <span class="nav-text">4.高性能</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-%E5%B9%B3%E5%8F%B0%E5%8C%96%EF%BC%8C%E5%9B%BD%E9%99%85%E5%8C%96"><span class="nav-number">5.</span> <span class="nav-text">5.平台化，国际化</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BB%A3%E7%A0%81%E5%88%86%E6%9E%90"><span class="nav-number"></span> <span class="nav-text">代码分析</span></a></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">wwwttttj</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">8</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://gitee.com/wwwttttj" title="gitee → https:&#x2F;&#x2F;gitee.com&#x2F;wwwttttj" rel="noopener" target="_blank"><i class="fab fa-gitee fa-fw"></i>gitee</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">wwwttttj</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
